﻿using BLL;
using Model;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.BLL;
using 后整理管理系统.其他窗体;
using 后整理管理系统.自定义类;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.新增窗体;
using 纺织贸易管理系统.设置窗体;
using 纺织贸易管理系统.选择窗体;

namespace 纺织贸易管理系统.报表窗体
{
    public partial class 来货入库单 : Form
    {
        public DanjuTable danju { get; set; }
        private List<danjumingxitable> danjumingxis = new List<danjumingxitable>();
        private DataTable FineCodeTable = new DataTable();
        private List<WarehousingDetailCode> detaicodelist = new List<WarehousingDetailCode>();
        public FormUseful Useful { get; set; }
        private int rowindex = 0;
        public 来货入库单()
        {
            InitializeComponent();
            uiDatePicker1.Value = DateTime.Now;
            CreateGrid.Create(this.Name, gridView1);
            txtckmc.Text = QueryTime.DefaultStock;
            try
            {
                gridView1.Columns["Bianhao"].ColumnEdit = ButtonEdit1;
                gridView1.Columns["pingming"].ColumnEdit = ButtonEdit1;
                gridView1.Columns["danwei"].ColumnEdit = cmddanwei;
                gridView1.Columns["yanse"].ColumnEdit = colorbtn;
                gridView1.Columns["ColorNum"].ColumnEdit = colorbtn;
                gridView1.IndicatorWidth = 30;
            }
            catch
            {
                配置列ToolStripMenuItem_Click(null, null);
            }
        }
        private void Init()
        {
            if (Useful == FormUseful.新增)
            {
                danju = new DanjuTable();
                txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.生产入库单, uiDatePicker1.Value, DanjuLeiXing.入库单);
                txtkehu.Text = "";
                txtFahuodanwei.Text = string.Empty;
                txtbeizhu.Text = string.Empty;
                danjumingxis.Clear();
                for (int i = 0; i < 30; i++)
                {
                    danjumingxis.Add(new danjumingxitable() { danwei = "米", ganghao = string.Empty, yanse = string.Empty, houzhengli = string.Empty });
                }
                gridControl1.DataSource = danjumingxis;
                gridControl1.RefreshDataSource();
                uiDatePicker1.Value = DateTime.Now;
                uiDatePicker1.Enabled = true;
                cmbJincangyuanying.Text = "首次加工";
            }
            else
            {
                txtdanhao.Text = danju.dh;
                txtkehu.Text = danju.ksmc;
                uiDatePicker1.Value = danju.rq;
                txtckmc.Text = danju.ckmc;
                txtbeizhu.Text = danju.bz;
                txtFahuodanwei.Text = danju.fromDanhao;
                uiDatePicker1.Enabled = false;
                cmbJincangyuanying.Text = danju.jiagongleixing;
                if (Useful == FormUseful.查看)
                {
                    danjumingxis = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == danju.dh );
                }
                else
                {
                    danjumingxis = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == danju.dh && x.toupimishu == 0);
                }
                detaicodelist = Connect.CreatConnect().Query<WarehousingDetailCode>(x => x.DocNum == txtdanhao.Text);
                for (int i = danjumingxis.Count; i < 30; i++)
                {
                    danjumingxis.Add(new danjumingxitable() { danwei = "米", ganghao = string.Empty, yanse = string.Empty, houzhengli = string.Empty });
                }
                gridControl1.DataSource = danjumingxis;
                gridControl1.RefreshDataSource();
                if (Useful == FormUseful.查看)
                {
                    新增ToolStripMenuItem.Enabled = false;
                    gridView1.OptionsBehavior.Editable = false;
                }
            }
        }
        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.CloseEditor();
            if (uiDatePicker1.Value.ToShortDateString() != DateTime.Today.ToShortDateString())
            {
                if (MessageBox.Show("单据日期与系统日期不匹配？\r\n是否继续保存", this.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                {
                    return;
                }
            }
            //检查是否存在相同信息
            var mingxi = danjumingxis.Where(x => !string.IsNullOrEmpty(x.pingming)).ToList();
            foreach (var m in mingxi)
            {
                if (mingxi.Where(x => x.pingming == m.pingming && x.ganghao == m.ganghao && x.yanse == m.yanse).Count() > 1)
                {
                    Tools.ShowMessageBox.ShowErrorBox($"存在重复信息！品名一样  缸号一样\r\n品名是:{m.pingming}\r\n缸号是:{m.ganghao}");
                    return;
                }
            }
            //检查是否有空缸号和空信息
            if (danjumingxis.Where(x => !string.IsNullOrEmpty(x.pingming.Trim()) && string.IsNullOrEmpty(x.ganghao)).Count() > 0)
            {
                Sunny.UI.UIMessageBox.Show("存在空缸号记录，\r\n请检查输入的信息");
                return;
            }
            if (danjumingxis.Where(x => !string.IsNullOrEmpty(x.pingming.Trim()) && x.chengpingmishu == 0).Count() > 0)
            {
                Sunny.UI.UIMessageBox.Show("存在0米数记录，\r\n请检查输入的信息");
                return;
            }
            if (danjumingxis.Where(x => !string.IsNullOrEmpty(x.pingming.Trim()) && x.chengpingjuanshu == 0).Count() > 0)
            {
                Sunny.UI.UIMessageBox.Show("存在0卷数记录，\r\n请检查输入的信息");
                return;
            }
            //检查日期
            if (Useful == FormUseful.新增)
            {
                if (uiDatePicker1.Value.Date != DateTime.Now.Date)
                {
                    if (Sunny.UI.UIMessageBox.ShowAsk("单据日期与系统日期不相等！\r\n是否将单据日期调整为系统日期？"))
                    {
                        uiDatePicker1.Value = DateTime.Now;
                        txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.生产入库单, uiDatePicker1.Value, DanjuLeiXing.入库单);
                        foreach (var d in danjumingxis)
                        {
                            d.rq = uiDatePicker1.Value;
                            d.danhao = txtdanhao.Text;
                        }
                    }
                }
            }
            ///检查输入的客户是否存在客户资料中       
            var lianxiren = LXRService.GetOneLXR(x => x.MC == txtkehu.Text);
            if (string.IsNullOrWhiteSpace(lianxiren.MC))
            {
                Sunny.UI.UIMessageBox.Show($"该客户{txtkehu.Text}名称在客户资料中没有匹配到！\r\n请检查输入的客户名是否正确");
                return;
            }
            else
            {
                danju.ksbh = lianxiren.BH;
                if (QueryTime.IsMustNeedTel)
                {
                    if (string.IsNullOrEmpty(lianxiren.DH))
                    {
                        Tools.ShowMessageBox.ShowErrorBox("当前策略为客户必须要有联系电话！检测不到该客户的联系电话！");
                        return;
                    }
                }
            }
            ///
            if (string.IsNullOrWhiteSpace(txtFahuodanwei.Text))
            {
                UIMessageBox.ShowError("发货地址不能为空！\r\n请输入发货地址");
                return;
            }
            if (string.IsNullOrWhiteSpace(cmbJincangyuanying.Text))
            {
                UIMessageBox.ShowError("进仓原因不能为空！\r\n请选择进仓原因");
                return;
            }
            if (string.IsNullOrEmpty(txtkehu.Text))
            {
                Tools.ShowMessageBox.ShowErrorBox("客户名称必须填写！保存失败");
                return;
            }
            if (danjumingxis.Where(x=>x.yanse.Contains ("/")).Count()>0)
            {
                Tools.ShowMessageBox.ShowErrorBox("颜色当中不能包含 / 这个字符，请用其他字符替换 ！保存失败");
                return;
            }
            try
            {

                gridView1.CloseEditor();
                if (danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming.Trim())).ToList().Count == 0)
                {
                    Sunny.UI.UIMessageBox.ShowError("保存失败！没有任何布料！如果有布料品名必须要填写!");
                    return;
                }
                if (string.IsNullOrWhiteSpace(txtkehu.Text))
                {
                    Sunny.UI.UIMessageBox.ShowError("保存失败！请选择客户");
                    return;
                }
                if (string.IsNullOrWhiteSpace(txtckmc.Text))
                {
                    Sunny.UI.UIMessageBox.ShowError("保存失败！请选择仓库名称");
                    return;
                }
                danju.bz = txtbeizhu.Text;
                danju.ksmc = txtkehu.Text.TrimEnd(' ');
                danju.dh = txtdanhao.Text;
                danju.djlx = DanjuLeiXing.入库单;
                danju.rq = uiDatePicker1.Value;
                danju.ckmc = txtckmc.Text;
                danju.StockName = cmbcunfang.Text.TrimEnd(' ');
                danju.totaljuanshu = danjumingxis.Sum(x => x.chengpingjuanshu);
                danju.TotalMishu = danjumingxis.Sum(x => x.chengpingmishu);
                danju.zhuangtai = "未审核";
                danju.own = Tools.CurrentUser.user.YHBH;
                //进仓原因
                danju.jiagongleixing = cmbJincangyuanying.Text;
                ///fromDanhao就是真实的发货地址
                danju.fromDanhao = txtFahuodanwei.Text;
                foreach (var m in danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming.Trim())).ToList())
                {
                    m.danhao = danju.dh;
                    m.CustomName = danju.ksmc;
                    m.rkdh = danju.dh;
                    m.InventoryQuantity = m.chengpingmishu;
                    m.suolv = 0;
                    m.rq=danju.rq;
                    m.FabricStyle = cmbfabricstyle.Text;
                }
                using (var trans = Connect.dbcontext.UseTran())
                {
                    if (Useful == FormUseful.新增)
                    {
                        danju.dh = 单据BLL.检查单号(danju.dh);

                        if (!CheckStockBLL.CheckStock(danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList()))
                        {
                            return;
                        }
                        Connect.dbcontext.Insertable(danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList()).ExecuteCommand();
                        if (SysInfo.GetInfo.own != "审核制")
                        {
                            danju.zhuangtai = "已审核";
                        }
                        else
                        {
                            danju.zhuangtai = "未审核";
                        }
                        Connect.dbcontext.Insertable(danju).ExecuteCommand();
                        生产入库单BLL.保存(danju, danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList());
                    }
                    else
                    {

                        生产入库单BLL.修改单据(danju, danjumingxis);
                        Connect.dbcontext.Deleteable<WarehousingDetailCode>(x => x.DocNum == txtdanhao.Text).ExecuteCommand();
                        Connect.dbcontext.Insertable(detaicodelist).ExecuteCommand();
                    }
                    trans.CommitTran();
                }

                AlterDlg.Show("保存成功");
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowErrorBox("保存单据的时候发生了错误" + ex.Message);
                return;
            }
            if (Useful == FormUseful.新增)
            {
                if (Sunny.UI.UIMessageBox.ShowAsk("是否直接开生产流转卡？\r\n直接开按确定。否则按取消"))
                {
                    MainForm.mainform.CloseTab();
                    MainForm.mainform.AddMidForm(new 流转卡() { danjumingxis = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == txtdanhao.Text), Useful = FormUseful.复制, danju = danju });

                }
                else
                {
                    if (ShowMessageBox.ShowAskBox("是否继续新增操作？") == DialogResult.Yes)
                    {
                        Useful = FormUseful.新增;
                        //清空所有控件
                        Init();
                    }
                    else
                    {
                        MainForm.mainform.CloseTab();
                    }
                }
            }
            else
            {
                if (Useful == FormUseful.修改)
                {
                    if (this.ShowAskDialog("是否直接开生产流转卡？\r\n直接开按确定。否则按取消"))
                    {
                        MainForm.mainform.CloseTab();
                        MainForm.mainform.AddMidForm(new 流转卡() { danjumingxis = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == txtdanhao.Text), Useful = FormUseful.复制, danju = danju });
                    }
                    else
                    {
                        if (ShowMessageBox.ShowAskBox("是否继续新增操作？") == DialogResult.Yes)
                        {
                            Useful = FormUseful.新增;
                            //清空所有控件
                            Init();
                        }
                        else
                        {
                            MainForm.mainform.CloseTab();
                        }
                    }
                        
                    }
                    else
                    {
                        if (this.ShowAskDialog("是否直接开生产流转卡？\r\n直接开按确定。否则按取消"))
                        {
                            MainForm.mainform.CloseTab();
                            MainForm.mainform.AddMidForm(new 流转卡() { danjumingxis = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == txtdanhao.Text), Useful = FormUseful.复制, danju = danju });
                        }
                        else
                        {
                            if (ShowMessageBox.ShowAskBox("是否继续新增操作？") == DialogResult.Yes)
                            {
                                Useful = FormUseful.新增;
                                //清空所有控件
                                Init();
                            }
                            else
                            {
                                MainForm.mainform.CloseTab();
                            }
                        }
                    }
                }
        }
        private void txtkehu_ButtonCustomClick(object sender, EventArgs e)
        {
            var fm = new 客户选择();
            fm.ShowDialog();
            if (fm.linkman != null)
            {
                danju.ksbh = fm.linkman.BH;
                txtkehu.Text = fm.linkman.MC;
                if (!string.IsNullOrWhiteSpace(fm.linkman.bz))
                {
                    Sunny.UI.UIMessageBox.Show("该客户有特殊需求！\r\n需求是:" + fm.linkman.bz);
                }
            }
        }

        private void 复制行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rowindex = gridView1.FocusedRowHandle;
        }

        private void 粘贴行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopyRow.Copy<danjumingxitable>(danjumingxis, rowindex, gridView1, gridView1.FocusedRowHandle, this);
        }

        private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var row = gridView1.GetFocusedRow() as danjumingxitable;
            if (!string.IsNullOrEmpty(row.offerid))
            {
                ShowMessageBox.ShowErrorBox("该行已经有开卡记录，不能删除！");
                return;
            }
            if (row.toupimishu>0)
            {
                ShowMessageBox.ShowErrorBox("该行已经有发货数，不能删除！");
                return;
            }
            if (row.ExitsNum > 0)
            {
                ShowMessageBox.ShowErrorBox("该行已经有退仓记录，不能删除！");
                return;
            }
            gridView1.DeleteRow(gridView1.FocusedRowHandle);
        }

        private void 添加行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            danjumingxis.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = uiDatePicker1.Value });
            gridControl1.RefreshDataSource();
        }

        private void 配置列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView1) { formname = this.Name, Obj = new danjumingxitable() };
            fm.ShowDialog();
        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView1);
        }

        private void txtckmc_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var fm = new 仓库选择();
            fm.ShowDialog();
            txtckmc.Text = fm.stock.mingcheng;
        }

        private void ButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var fm = new 品种选择();
                fm.ShowDialog();
                var i = gridView1.FocusedRowHandle;
                foreach (var pingzhong in fm.pingzhong)
                {
                    danjumingxis[i].bizhong = "人民币￥";
                    danjumingxis[i].Bianhao = pingzhong.bh;
                    danjumingxis[i].guige = pingzhong.gg;
                    danjumingxis[i].chengfeng = pingzhong.cf;
                    danjumingxis[i].pingming = pingzhong.pm;
                    danjumingxis[i].kezhong = pingzhong.kz;
                    danjumingxis[i].menfu = pingzhong.mf;
                    danjumingxis[i].danwei = "米";
                    i++;
                    if (i == danjumingxis.Count - 1)
                        for (int j = 0; j < 30; j++)
                        {
                            danjumingxis.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = Convert.ToDateTime(uiDatePicker1.Text) });
                        }
                }
                fm.Dispose();
                gridControl1.RefreshDataSource();
                gridView1.CloseEditor();
            }
        }

        private void 选择工艺ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 工序选择();
            fm.ShowDialog();
            foreach (var t in fm.technologyTables)
            {
                txtbeizhu.Text += t.Technology + "+";
            }
            if (txtbeizhu.Text.Length > 0)
                txtbeizhu.Text = txtbeizhu.Text.Substring(0, txtbeizhu.Text.Length - 1);
        }

        private void 复制单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridControl1.Focus();
            SendKeys.Send("^c");
        }

        private void 粘贴单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridControl1.Focus();
            SendKeys.Send("^v");
        }

        private void txtkehu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var fm = new 客户选择();
                fm.linkman.ZJC = txtkehu.Text;
                fm.linkman.MC = string.Empty;
                fm.ShowDialog();
                if (fm.linkman != null)
                {
                    danju.ksbh = fm.linkman.BH;
                    txtkehu.Text = fm.linkman.MC;
                }
            }
        }

        private void txtckmc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var fm = new 仓库选择() { stock = new StockInfoTable { Zhujici = txtckmc.Text } };
                fm.ShowDialog();
                txtckmc.Text = fm.stock.mingcheng;
            }
        }

        private void 相同品名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var pingming = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[0], "pingming").ToString();
            foreach (var row in gridView1.GetSelectedRows())
            {
                gridView1.SetRowCellValue(row, "pingming", pingming);
            }
        }

        private void 相同颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var yanse = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[0], "yanse").ToString();
            foreach (var row in gridView1.GetSelectedRows())
            {
                gridView1.SetRowCellValue(row, "yanse", yanse);
            }
        }

        private void txtckmc_ButtonClick(object sender, EventArgs e)
        {
            var fm = new 仓库选择() { stock = new StockInfoTable { Zhujici = txtckmc.Text } };
            fm.ShowDialog();
            txtckmc.Text = fm.stock.mingcheng;
        }

        private void 来货入库单_Load(object sender, EventArgs e)
        {
            Init();
        }

        private void 输入细码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (detaicodelist.Count == 0)
            {
                var fm = new 输入来货细码()
                {
                    useful = FormUseful.新增,
                    dt = FineCodeTable,
                    mingxilist = danjumingxis.Where(x => x.pingming != null).ToList()
                };
                fm.ShowDialog();
            }
            else
            {
                FineCodeTable = new DataTable();

                foreach (var col in detaicodelist.Select(x => x.LotNum).Distinct())
                {
                    int rowindex = 0;
                    FineCodeTable.Columns.Add(col);
                    foreach (var d in detaicodelist.Where(x => x.LotNum == col).ToList())
                    {
                        if (rowindex == FineCodeTable.Rows.Count)
                        {
                            FineCodeTable.Rows.Add();
                        }
                        FineCodeTable.Rows[rowindex][col] = d.Length;
                        rowindex++;
                    }
                }
                var fm = new 输入来货细码()
                {
                    useful = FormUseful.修改,
                    dt = FineCodeTable,
                    mingxilist = danjumingxis.Where(x => x.pingming != null).ToList()
                };
                fm.ShowDialog();
            }
            detaicodelist.Clear();
            foreach (DataColumn col in FineCodeTable.Columns)
            {
                foreach (DataRow row in FineCodeTable.Rows)
                {
                    detaicodelist.Add(new WarehousingDetailCode { DocNum = txtdanhao.Text, LotNum = col.ColumnName, Length = row[col] == null ? string.Empty : row[col].ToString() });
                }
            }
            gridControl1.RefreshDataSource();
        }

        private void 打印编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintDanju(PrintModel.Design);
        }
        private void InitDanju()
        {
            danju.bz = txtbeizhu.Text;
            danju.ksmc = txtkehu.Text.TrimEnd(' ');
            danju.dh = txtdanhao.Text;
            danju.djlx = DanjuLeiXing.入库单;
            danju.rq = uiDatePicker1.Value;
            danju.ckmc = txtckmc.Text;
            danju.StockName = cmbcunfang.Text.TrimEnd(' ');
            danju.totaljuanshu = danjumingxis.Sum(x => x.chengpingjuanshu);
            danju.TotalMishu = danjumingxis.Sum(x => x.chengpingmishu);
            danju.zhuangtai = "未审核";
            danju.own = Tools.CurrentUser.user.YHBH;
            //进仓原因
            danju.jiagongleixing = cmbJincangyuanying.Text;
            ///fromDanhao就是真实的发货地址
            danju.fromDanhao = txtFahuodanwei.Text;
            foreach (var m in danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList())
            {
                m.danhao = danju.dh;
                m.CustomName = danju.ksmc;
                m.rkdh = danju.dh;
                m.InventoryQuantity = m.chengpingmishu;
                m.suolv = 0;
            }
        }
        private void PrintDanju(PrintModel useful)
        {
            if (useful == PrintModel.Design)
            {
                if (!PrintService.CheckPrintDesignAccess())
                {
                    return;
                }
            }

            InitDanju();
            new Tools.打印发货单()
            {
                danjuTable = danju,
                danjumingxitables = danjumingxis .Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList(),
                danjuinfo = new Tools.FormInfo() { FormName = "销售发货单查询", GridviewName = gridView1.Name },
                mingxiinfo = new Tools.FormInfo() { FormName = this.Name, GridviewName = gridView1.Name },
                Rukuxima=FineCodeTable
            }.Print( PrintPath.报表模板 + "进仓单.frx", useful);
        }

        private void 打印预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintDanju(PrintModel.Privew);
        }

        private void 直接打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintDanju(PrintModel.Print);
        }
    }
}
